import { constantRoutes } from '@/router'
import Layout from '@/layout'
const modulesFiles = require.context('@/views', true, /\.vue$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const compoent = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
//  function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.includes(role))
//   } else {
//     return true
//   }
// }
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(roles = [], pid = 0) {
  const res = []
  roles.forEach((item) => {
    const items = {
      path: item.path,
      name: item.path,
      component: item.component ? compoent[item.component] : Layout,
      hiden: item.visible !== '1',
      meta: {
        title: item.menuName,
        icon: item.icon
      }
    }
    if (item.parentId === pid) {
      items.children = filterAsyncRoutes(roles, item.id)
      if (items.children.length < 1) {
        delete items.children
      }
      if (!item.component) {
        items.redirect = items.path
      }
      res.push(items)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)

    // console.log(constantRoutes.concat(routes))
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve([...accessedRoutes, ...constantRoutes])
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
